const express = require('express');
const app = express();
const mysql = require('mysql2');
const Blog = require('../services/blogServices');
const tagBlog = require("../services/tagServices")


// 静态私服
const path = require('path');
app.use(express.static(path.resolve(__dirname, "../blogWeb")));
app.listen(5000, () => {
    console.log("listen 5000");
});




// 连接数据库
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'blog'
})

// 处理post参数
app.use(express.urlencoded({ extended: true }));
// 处理json参数
app.use(express.json())


// 上传图片
app.use("/upload", require("./upload"));

/**
 * 设置CORS允许跨域
 */
app.all("*", (req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    next();
});



// 用户信息请求
app.get("/admin", (req, res) => {
    let tags_count;
    connection.query("SELECT COUNT(id) FROM tags;", function (err, result) {
        tags_count = result[0]['COUNT(id)']
    })
    connection.query("SELECT * FROM admins;", function (err, result) {
        result.push(tags_count)
        res.send(result);
    })
})


app.use("/blog", require("./app/blogApi"))


app.get("/abstract_tags", (req, res) => {
    connection.query(`SELECT BLOGID,TAGID,tag FROM blogs,tags,blogtags WHERE blogs.id=blogtags.BlogId and
    blogtags.TagId=tags.id;`, function (err, result) {
        res.send(result);
    })
})



app.get("/blogTag", async (req, res) => {
    const result = await tagBlog.getBlogTag()
    res.send(result)
})



// 标签页
app.get("/tags", (req, res) => {
    connection.query(`SELECT BLOGID,TAGID,tag,title,abstract,publishTime FROM blogs,tags,blogtags WHERE blogs.id=blogtags.BlogId and
    blogtags.TagId=tags.id;`, function (err, result) {
        res.send(result);
    })
})


// 分类标签页
app.get("/category_tag", (req, res) => {
    connection.query(`SELECT BLOGID,title,abstract,publishTime,tag FROM blogs,tags,blogtags WHERE blogs.id=blogtags.BlogId and
    blogtags.TagId=tags.id;`, function (err, result) {
        res.send(result);
    })
})


app.get("/archives_date", (req, res) => {
    connection.query(`SELECT BLOGID,title,publishTime FROM blogs,tags,blogtags WHERE blogs.id=blogtags.BlogId and
    blogtags.TagId=tags.id;`, function (err, result) {
        res.send(result);
    })
})
